

/**
 * @author jacobbj
 *
 */
public class GameBoard {

	public static final int EMPTY = 0;
	public static final int PLAYER1 = 1;
	public static final int PLAYER2 = 2;

	private static final float EmptyFieldfactor = (float) 0.05;

	int columns;
	int rows;
	int[][] board;
	int[] coinsInColumn;
	int moves;

	public GameBoard() {
		columns = 7;
		rows = 6;
		moves = 0;
		this.board = new int[columns][rows];
		this.coinsInColumn = new int[columns];

		clearBoard(this);
	}

	public GameBoard(int c, int r) {
		columns = c;
		rows = r;
		moves = 0;
		this.board = new int[columns][rows];
		this.coinsInColumn = new int[columns];

		clearBoard(this);

	}

	public GameBoard(GameBoard aBoard) {
		columns = aBoard.getNumColumns();
		rows = aBoard.getNumRows();
		moves = 0;
		this.board = new int[columns][rows];
		this.coinsInColumn = new int[columns];
		// copy board
		for (int i = 0; i < columns; i++ ) {
			this.coinsInColumn[i] = aBoard.getCoinsInColumns()[i];
			for (int j=rows-1 ; j >= 0 ; j--) {
				this.board[i][j] = aBoard.getBoardArray()[i][j];
			}
		}
	}

	public static void clearBoard(GameBoard g) {

		for (int i = 0; i < g.columns; i++ ) {
			g.coinsInColumn[i] = 0;
			for (int j= g.rows-1 ; j >= 0 ; j--) {
				g.board[i][j] = GameBoard.EMPTY;
			}
		}
	}
		
	public GameBoard insertInColumn(int col, int player) {
		int index = col-1;
		this.board[index][coinsInColumn[index]++] = player;
		moves++;
		return this;
	}

	public boolean columnEmpty(int col) {
		return(coinsInColumn[col-1] == 0);
	}

	public boolean isFull() {
		return (moves == (rows * columns));
	}
	
	public int numberOfMoves() {
		int moves = 0;
		for (int i = 0; i < this.columns; i++) {
			moves += coinsInColumn[i];
		}
		
		return moves;
	}
	
	public String toString() {

		String result = "";
		for (int i = (rows-1) ; i >= 0 ; i-- ) {
			result += "[ ";
			for (int j = 0 ; j < columns ; j++) {
				result += this.board[j][i] + " ";
			}
			result += "] \n";
		}

		return result;
	}

	public GameBoard get() {
		return this;
	}

	public int getNumColumns() {
		return this.columns;
	}

	public int getNumRows() {
		return this.rows;
	}

	public int[][] getBoardArray() {
		return this.board;
	}

	public int[] getCoinsInColumns() {
		return this.coinsInColumn;
	}


	/**
	 * @param col
	 * @param player
	 * @return returns a new gameboard with
	 */
	public GameBoard peakColumn(int col, int player) {
			
		if ( !(col > columns)  && (board[col-1][rows-1] == EMPTY))
			return (new GameBoard(this)).insertInColumn(col, player);
		else return null;
	} 

}
